import pygame
import math

# 初始化 Pygame
pygame.init()

# 定义常量
WIDTH, HEIGHT = 800, 600
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
TRACK_WIDTH = 10
CAR_WIDTH = 30
CAR_HEIGHT = 20

# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("过山车游戏")

# 定义轨道（简单的正弦波轨道示例）
track_points = []
for x in range(0, WIDTH, 10):
    y = int(HEIGHT / 2 + 100 * math.sin(x / 100))
    track_points.append((x, y))


class RollerCoasterCar:
    def __init__(self):
        self.position = 0
        self.speed = 2

    def move(self):
        self.position += self.speed
        if self.position >= len(track_points):
            self.position = 0

    def draw(self):
        current_point = track_points[int(self.position)]
        next_point = track_points[(int(self.position) + 1) % len(track_points)]
        dx = next_point[0] - current_point[0]
        dy = next_point[1] - current_point[1]
        angle = math.atan2(dy, dx)
        car_surface = pygame.Surface((CAR_WIDTH, CAR_HEIGHT))
        car_surface.fill(RED)
        rotated_car = pygame.transform.rotate(car_surface, -math.degrees(angle))
        car_rect = rotated_car.get_rect(center=current_point)
        screen.blit(rotated_car, car_rect)


# 创建过山车
roller_coaster = RollerCoasterCar()

# 游戏主循环
clock = pygame.time.Clock()
running = True
while running:
    screen.fill(WHITE)

    # 处理事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                roller_coaster.speed += 1
            elif event.key == pygame.K_DOWN:
                if roller_coaster.speed > 1:
                    roller_coaster.speed -= 1

    # 绘制轨道
    for i in range(len(track_points) - 1):
        pygame.draw.line(screen, BLACK, track_points[i], track_points[i + 1], TRACK_WIDTH)

    # 移动并绘制过山车
    roller_coaster.move()
    roller_coaster.draw()

    # 更新显示
    pygame.display.flip()
    clock.tick(60)

# 退出游戏
pygame.quit()